use gloo::console::error;
use thiserror::Error;
use wasm_bindgen::JsValue;
use web_sys::Element;

#[derive(Error, Debug)]
pub enum MyError {
    #[error("RequestError:{0}")]
    RequestError(#[from] gloo_net::Error),
    #[error("ParseIntError:{0}")]
    ParseIntError(#[from] std::num::ParseIntError),
    #[error("custom error:{0}")]
    Msg(String),
}

impl MyError {
    pub fn custom(msg: &str) -> Self {
        MyError::Msg(msg.to_string())
    }
}

impl From<JsValue> for MyError {
    fn from(val: JsValue) -> Self {
        MyError::custom(&format!("{:?}", val))
    }
}
impl From<Element> for MyError {
    fn from(val: Element) -> Self {
        MyError::custom(&format!("{:?}", val))
    }
}
pub type MyResult<T> = std::result::Result<T, MyError>;
pub trait ErrLogger<T> {
    fn log_if_err(&self) -> &Self;
}
impl<T> ErrLogger<T> for MyResult<T> {
    fn log_if_err(&self) -> &Self {
        if let Err(err) = self.as_ref() {
            error!(format!("panic: {:}", err));
        }
        self
    }
}

pub fn log_error<T>(result: MyResult<T>, prefix: Option<String>) {
    if let Err(err) = result {
        error!(format!("error prefix:{:?}: {:?}", prefix, err));
    }
}
